package com.lsq.baseadmin.common.interceptor;

import com.lsq.baseadmin.common.exception.MyException;
import com.lsq.baseadmin.modules.maintenance.entity.Menu;
import com.lsq.baseadmin.modules.manage.utils.AuthUtil;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 菜单权限拦截器
 * @author pc12138
 * @since 2020/10/24 11:53
 */
public class MenuInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            String requestUrl = request.getServletPath();

            // 时不时会收到 /error 的请求
            String error = "/error";
            if (error.equals(requestUrl)) {
                return true;
            }

            if(!checkMyMenu(requestUrl, request.getSession())) {
                throw new MyException(HttpStatus.FORBIDDEN, "您没有权限，无法访问！");
            }
            return true;
        }
        return true;
    }

    private boolean checkMyMenu(String requestUrl, HttpSession session) {
        List<Menu> list = AuthUtil.getLoginUser(session).getMyMenus();
        for (Menu menu : list) {
            if (requestUrl.equals(menu.getPath())) {
                return true;
            }
        }
        return false;
    }
}
